package com.drawu.drawuspring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drawu.drawuspring.constants.BehaviorConstants;
import com.drawu.drawuspring.domain.DTO.LikesBehaviorDto;
import com.drawu.drawuspring.domain.po.LikedRecord;
import com.drawu.drawuspring.domain.po.Users;
import com.drawu.drawuspring.mapper.LikedRecordMapper;
import com.drawu.drawuspring.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drawu.drawuspring.utils.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author hui
 * @since 2024-10-12
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {


    private final StringRedisTemplate redisTemplate;
    /**
     * 保存点赞记录
     *
     */
    @Override
    public void saveRecord(LikesBehaviorDto dto) {
        LikedRecord record = new LikedRecord();
        Users user = AppThreadLocalUtil.getUser();
        record.setUserId(String.valueOf(user.getId()));
        record.setPostsId(dto.getPostsId());
        save(record);
    }

    /**
     * 删除点赞记录
     *
     */
    @Override
    public void deleteRecord(LikesBehaviorDto dto) {
        QueryWrapper<LikedRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", String.valueOf(AppThreadLocalUtil.getUser().getId()))
               .eq("posts_id", dto.getPostsId());
        remove(wrapper);

    }

    /**
     * 获取用户点赞过的记录
     *
     */
    @Override
    public Set<Integer> getLikedRecordList(List<Integer> postIds) {
        //判断用户是否登录
        Users user = AppThreadLocalUtil.getUser();
        if (user == null || user.getId() == null) {
            throw new RuntimeException("用户未登录");
        }
        //查询用户点赞过的记录
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Integer postId : postIds) {
                String key = BehaviorConstants.LIKE_BEHAVIOR + postId;
                src.sIsMember(key,  String.valueOf(user.getId()));
            }
            return null;
        });
        // 创建从0到集合size的流
        // 遍历每个元素，保留结果为true的角标i
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(postIds::get)
                .collect(Collectors.toSet());// 收集9
    }
}
